package base.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.internal.LinkedTreeMap;
import com.tange.ai.iot.client.gnssa.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import base.http.rxandroid.CustomDisposableForJava;
import base.http.utils.ConsumerDialog;
import base.http.utils.RetrofitManager;
import base.utils.LogUtil;
import base.utils.SysUtils;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;


/**
 * 说明：
 * Created by jjs on 2018/11/23
 */

public abstract class BaseActivity extends AppCompatActivity {

    /*** 两次点击提示退出 */
    private long mStart;
    protected boolean mDoubleClick2Exit = false;//是否需要双击退出拦截提示
    /*** 状态栏相关 */
    protected boolean mTranslucentStatus = false;//透明状态栏
    protected boolean mStatusBarHidden = false;//隐藏状态栏
    @ColorInt
    protected int mStatusBarColor = -1;//状态栏的颜色 int值
    protected boolean hasFitsSystemWindows = true;//是否需要向下挤压

    /*** 常量 */
    private Unbinder mUnBinder;
    protected boolean hasFragmentResult = true;//是否需要fragment回调

    /**
     * 获取电源锁，实现屏幕长亮控制
     */
    private PowerManager mPowerManager;
    private PowerManager.WakeLock mWakeLock;
    private boolean isKeepScreenOn;
    public Context mContext;

    private String TAG = "BaseActivity";
    protected ConsumerDialog dialogLoad;

    @SuppressLint("InvalidWakeLockTag")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (mStatusBarHidden) {
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        super.onCreate(savedInstanceState);
        if (getLayoutId() != 0) {
            setContentView(getLayoutId());
        }
        try {
            EventBus.getDefault().register(this);
        } catch (Exception e) {
            // e.printStackTrace();
        }
        mContext = this;
        mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = mPowerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MY_LOCK");

        dialogLoad = new ConsumerDialog(mContext);
        dialogLoad.setCancelable(false);
        if (!mStatusBarHidden) {
            if (mTranslucentStatus) {
                //设置透明色
                mStatusBarColor = 0x00000000;
                hasFitsSystemWindows = false;
            } else {
                //设置具体颜色
                if (mStatusBarColor == -1) {
                    mStatusBarColor = getResources().getColor(R.color.purple_700);
                }
            }
        }
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            KeyboardUtils.hideSoftInput(this);
            EventBus.getDefault().unregister(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        mUnBinder = ButterKnife.bind(this);
    }

    protected abstract int getLayoutId();

    protected abstract void initData();

    protected void onActivityResultOK(int requestCode, Intent data) {

    }

    /*** 跳转相关 **/
    public void readyGo(Class<?> clazz, String key, String value, int requestCode) {
        Bundle bundle = new Bundle();
        bundle.putString(key, value);
        readyGo(clazz, bundle, requestCode);
    }

    public void readyGo(Class<?> clazz, String key, boolean value, int requestCode) {
        Bundle bundle = new Bundle();
        bundle.putBoolean(key, value);
        readyGo(clazz, bundle, requestCode);
    }

    public void readyGo(Class<?> clazz, String key, double value, int requestCode) {
        Bundle bundle = new Bundle();
        bundle.putDouble(key, value);
        readyGo(clazz, bundle, requestCode);
    }

    public void readyGo(Class<?> clazz, String key, int value, int requestCode) {
        Bundle bundle = new Bundle();
        bundle.putInt(key, value);
        readyGo(clazz, bundle, requestCode);
    }

    public void readyGo(Class<?> clazz, String key, Serializable value, int requestCode) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(key, value);
        readyGo(clazz, bundle, requestCode);
    }

    public void readyGo(Class<?> clazz) {
        readyGo(clazz, null, -1);
    }

    public void readyGo(Class<?> clazz, Bundle bundle) {
        readyGo(clazz, bundle, -1);
    }

    public void readyGo(Class<?> clazz, int requestCode) {
        readyGo(clazz, null, requestCode);
    }

    public void readyGo(Class<?> clazz, Bundle bundle, int requestCode) {
        LogUtil.INSTANCE.e("readyGo-跳转到activity:" + clazz.getName());
        if (clazz != null) {
            Intent intent = new Intent(this, clazz);
            if (null != bundle) {
                intent.putExtras(bundle);
            }
            if (requestCode == -1) {
                startActivity(intent);
            } else {
                startActivityForResult(intent, requestCode);
            }
        }
    }

    public void readyGoCleanTop(Class<?> clazz, Bundle bundle, int requestCode) {
        if (clazz != null) {
            Intent intent = new Intent(this, clazz);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            if (null != bundle) {
                intent.putExtras(bundle);
            }
            if (requestCode == -1) {
                startActivity(intent);
            } else {
                startActivityForResult(intent, requestCode);
            }
        }
    }


    @Override
    public void onBackPressed() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            getSupportFragmentManager().popBackStack();
            return;
        }
        if (!mDoubleClick2Exit) {
            finish();
        } else {
            long mend = System.currentTimeMillis();
            if (mend - mStart < 2000) {
                finish();
            } else {
                showShortToast("再按一次退出程序");
                mStart = mend;
            }
        }
    }


    public void showShortToast(String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.make().setBgColor(Color.parseColor("#FFFFFF")).setGravity(Gravity.CENTER, 0, 0)
                        .setTextColor(Color.parseColor("#040406"))
                        .show(str);
            }
        });
    }


  /*  @Override
    public <T> AutoDisposeConverter<T> bindAutoDispose() {
        return RxAutoDisposeUtils.bindAutoDispose(this);
    }*/

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            onActivityResultOK(requestCode, data);
        }
        if (hasFragmentResult) {
            for (Fragment fragment : getSupportFragmentManager().getFragments()) {
                fragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

    /**
     * 控制屏幕保持长亮的状态
     *
     * @param enabled true表示保持长亮，false表示不再保持长亮
     */
    public void keepScreenOn(boolean enabled) {
        if (mWakeLock != null) {
            if (enabled && !isKeepScreenOn) {
                mWakeLock.acquire();
            } else if (!enabled && isKeepScreenOn) {
                mWakeLock.release();
            } else {
                Log.i(this.getClass().getSimpleName(), "keep last state,the last state is " + "\"" + isKeepScreenOn + "\"");
            }
            isKeepScreenOn = enabled;
        } else {
            Log.i(this.getClass().getSimpleName(), "acqurie wake lock failed!");
        }
    }

    private static int sIsDebugMode = -1;

    public static boolean isDebugMode(Context context) {
        if (sIsDebugMode == -1) {
            boolean isDebug = context.getApplicationInfo() != null
                    && (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
            sIsDebugMode = isDebug ? 1 : 0;
        }
        return sIsDebugMode == 1;
    }

    /**
     * 权限检查
     *
     * @param neededPermissions 需要的权限
     * @return 是否全部被允许
     */
    protected boolean checkPermissions(String[] neededPermissions) {
        if (neededPermissions == null || neededPermissions.length == 0) {
            return true;
        }
        boolean allGranted = true;
        for (String neededPermission : neededPermissions) {
            allGranted &= ContextCompat.checkSelfPermission(this, neededPermission) == PackageManager.PERMISSION_GRANTED;
        }
        return allGranted;
    }

    protected void updateUI() {
    }


}
